// OpentTxl-C Version 11 safe file input/output
// J.R. Cordy, Jan 2023

// Copyright 2023, James R. Cordy and others

// Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
// and associated documentation files (the “Software”), to deal in the Software without restriction, 
// including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, 
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, 
// subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all copies 
// or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE 
// AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#define IO

// Safe C strings
#include "strings.h"

// Check interface consistency
#include "io.h"

// Table of open files
struct tffileT tffiles[tfmaxFiles];

int tflookahead;
int tfnextfile;

// Main program command line arguments
int    tfargc;
char **tfargv;

void tfopen (const int openMode, const string fileName, int *stream)
{
    // Do we have room to open another file?
    int sn;
    for (sn = tfnextfile; sn < tfmaxFiles - 3; sn++) {
        if (tffiles[sn + 2].file == NULL) break;
    }

    if (sn == tfmaxFiles - 3) {
        // Nope, return 0
        *stream = 0;
        return;
    }

    // Yes, let's use it
    *stream = sn;

    // Save the file name
    string *duplicate = (string *) malloc (sizeof (string));
    stringcpy (*duplicate, fileName);

    tffiles[*stream+2].name = *duplicate;

    switch (openMode) {
        case OPEN_BINARY_WRITE:
             tffiles[*stream+2].file = fopen (fileName, "wb");
             tffiles[*stream+2].mode = WRITE_MODE;
             break;
        case OPEN_CHAR_WRITE:
             tffiles[*stream+2].file = fopen (fileName, "w");
             tffiles[*stream+2].mode = WRITE_MODE;
             break;
        case OPEN_CHAR_APPEND:
             tffiles[*stream+2].file = fopen (fileName, "a");
             tffiles[*stream+2].mode = WRITE_MODE;
             break;
        case OPEN_BINARY_READ:
             tffiles[*stream+2].file = fopen (fileName, "rb");
             tffiles[*stream+2].mode = READ_MODE;
             break;
        case OPEN_CHAR_READ:
             tffiles[*stream+2].file = fopen (fileName, "r");
             tffiles[*stream+2].mode = READ_MODE;
             break;
    }

    if (tffiles[*stream+2].file == NULL) {
        *stream = 0;
    }
}

void tffetcharg (const int arg, string dest)
{
    if (arg <= tfargc) {
        stringcpy (dest, tfargv[arg]);
    } else {
        stringcpy (dest, "");
    }
}

void tfinitialize (const int argc, char **argv) 
{ 
    // Initialize standard streams
    const char * filename = "";

    tfnextfile = 0;
    filename = "stdin";
    tffiles[tfnextfile].file = stdin;
    tffiles[tfnextfile].name = filename;
    tffiles[tfnextfile].mode = READ_MODE;

    tfnextfile = 1;
    filename = "stdout";
    tffiles[tfnextfile].file = stdout;
    tffiles[tfnextfile].name = filename;
    tffiles[tfnextfile].mode = WRITE_MODE;

    tfnextfile = 2;
    tffiles[tfnextfile].file = stderr;
    filename = "stderr";
    tffiles[tfnextfile].name = filename;
    tffiles[tfnextfile].mode = WRITE_MODE;

    // Mark other streams as available
    filename = "";
    for (int i = tfnextfile + 1; i < tfmaxFiles; i++) {
        tffiles[i].file = NULL;
        tffiles[i].name = filename;
        tffiles[i].mode = READ_MODE;
    }

    // Initialize global argv and argc, associate positional file names
    tfargc = argc-1;
    tfargv = argv;
    for (int i = 1; i < argc && tfnextfile < tfmaxFiles; i++) {
        if (argv[i][0] != '-') {
            tfnextfile++;
            tffiles[tfnextfile].name = argv[i];
        }
    };
    tfnextfile++;
}

void tffinalize (void)
{
    // Flush all buffered output
    tfflush ();

    // Close all output streams, except stdin, stdout and stderr 
    for (int i = 3; i < tfmaxFiles; i++) {
        if (tffiles[i].file != NULL) {
            fclose (tffiles[i].file);
        }
    }
}
